// 外交管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Faction, Relationship, Treaty, DiplomaticAction, DiplomaticMission } from '@/types'
import { useResourcesStore } from './resources'

export const useDiplomacyStore = defineStore('diplomacy', () => {
  const resourcesStore = useResourcesStore()

  // 状态
  const factions = ref<Record<string, Faction>>({})
  const treaties = ref<Record<string, Treaty>>({})
  const diplomaticActions = ref<Record<string, DiplomaticAction>>({})
  const activeMissions = ref<Record<string, DiplomaticMission>>({})
  const playerFactionId = ref<string>('player')

  // 计算属性
  const alliedFactions = computed(() => {
    return Object.values(factions.value).filter(faction => {
      if (faction.id === playerFactionId.value) return false
      const relationship = faction.relationships[playerFactionId.value]
      return relationship && relationship.status === 'allied'
    })
  })

  const hostileFactions = computed(() => {
    return Object.values(factions.value).filter(faction => {
      if (faction.id === playerFactionId.value) return false
      const relationship = faction.relationships[playerFactionId.value]
      return relationship && (relationship.status === 'hostile' || relationship.status === 'war')
    })
  })

  const neutralFactions = computed(() => {
    return Object.values(factions.value).filter(faction => {
      if (faction.id === playerFactionId.value) return false
      const relationship = faction.relationships[playerFactionId.value]
      return relationship && relationship.status === 'neutral'
    })
  })

  const activeTreaties = computed(() => {
    return Object.values(treaties.value).filter(treaty => 
      treaty.isActive && treaty.participants.includes(playerFactionId.value)
    )
  })

  const diplomaticPower = computed(() => {
    const playerFaction = factions.value[playerFactionId.value]
    if (!playerFaction) return 0

    return playerFaction.strength.influence + 
           playerFaction.strength.economy * 0.3 + 
           playerFaction.strength.military * 0.2
  })

  // 动作
  function initializeFactions() {
    // 玩家派系
    factions.value[playerFactionId.value] = {
      id: playerFactionId.value,
      name: '人类联邦',
      type: 'federation',
      personality: {
        aggression: 30,
        cooperation: 70,
        expansion: 50,
        technology: 80,
        trade: 60
      },
      strength: {
        military: 100,
        economy: 100,
        technology: 100,
        influence: 100
      },
      territory: ['sol_system'],
      relationships: {},
      traits: [],
      isPlayer: true,
      isActive: true
    }

    // AI派系
    factions.value['zephyrian_empire'] = {
      id: 'zephyrian_empire',
      name: '泽菲利亚帝国',
      type: 'empire',
      personality: {
        aggression: 80,
        cooperation: 20,
        expansion: 90,
        technology: 60,
        trade: 40
      },
      strength: {
        military: 120,
        economy: 80,
        technology: 70,
        influence: 90
      },
      territory: ['zephyr_system', 'crimson_nebula'],
      relationships: {
        [playerFactionId.value]: {
          factionId: playerFactionId.value,
          status: 'neutral',
          opinion: -10,
          trust: 30,
          fear: 20,
          treaties: [],
          history: []
        }
      },
      traits: [
        {
          id: 'militaristic',
          name: '军国主义',
          description: '军事力量强大，倾向于武力解决问题',
          effects: [
            {
              type: 'military',
              modifier: 0.2,
              description: '军事力量+20%'
            }
          ]
        }
      ],
      isPlayer: false,
      isActive: true
    }

    factions.value['crystalline_collective'] = {
      id: 'crystalline_collective',
      name: '水晶集合体',
      type: 'collective',
      personality: {
        aggression: 10,
        cooperation: 90,
        expansion: 30,
        technology: 95,
        trade: 80
      },
      strength: {
        military: 60,
        economy: 110,
        technology: 140,
        influence: 70
      },
      territory: ['crystal_fields', 'resonance_system'],
      relationships: {
        [playerFactionId.value]: {
          factionId: playerFactionId.value,
          status: 'friendly',
          opinion: 40,
          trust: 60,
          fear: 5,
          treaties: [],
          history: []
        }
      },
      traits: [
        {
          id: 'technological',
          name: '科技先进',
          description: '拥有先进的科技和研究能力',
          effects: [
            {
              type: 'research',
              modifier: 0.3,
              description: '研究速度+30%'
            }
          ]
        }
      ],
      isPlayer: false,
      isActive: true
    }

    factions.value['void_hunters'] = {
      id: 'void_hunters',
      name: '虚空猎手',
      type: 'nomads',
      personality: {
        aggression: 95,
        cooperation: 5,
        expansion: 100,
        technology: 40,
        trade: 10
      },
      strength: {
        military: 150,
        economy: 40,
        technology: 50,
        influence: 30
      },
      territory: ['void_expanse'],
      relationships: {
        [playerFactionId.value]: {
          factionId: playerFactionId.value,
          status: 'hostile',
          opinion: -80,
          trust: 0,
          fear: 10,
          treaties: [],
          history: []
        }
      },
      traits: [
        {
          id: 'raiders',
          name: '掠夺者',
          description: '以掠夺和征服为生的游牧民族',
          effects: [
            {
              type: 'military',
              modifier: 0.25,
              description: '攻击力+25%'
            }
          ]
        }
      ],
      isPlayer: false,
      isActive: true
    }

    // 初始化玩家与其他派系的关系
    Object.values(factions.value).forEach(faction => {
      if (faction.id !== playerFactionId.value) {
        const playerFaction = factions.value[playerFactionId.value]
        if (playerFaction && !playerFaction.relationships[faction.id]) {
          playerFaction.relationships[faction.id] = {
            factionId: faction.id,
            status: 'neutral',
            opinion: 0,
            trust: 50,
            fear: 0,
            treaties: [],
            history: []
          }
        }
      }
    })
  }

  function proposeTreaty(targetFactionId: string, treatyType: Treaty['type'], terms: any[]): boolean {
    const targetFaction = factions.value[targetFactionId]
    const playerFaction = factions.value[playerFactionId.value]
    
    if (!targetFaction || !playerFaction) return false

    const relationship = playerFaction.relationships[targetFactionId]
    if (!relationship) return false

    // 检查外交状态是否允许提议条约
    if (relationship.status === 'war' && treatyType !== 'non_aggression') return false

    // 计算AI接受概率
    const acceptanceChance = calculateTreatyAcceptance(targetFaction, treatyType, terms)
    
    if (Math.random() < acceptanceChance) {
      // 创建条约
      const treatyId = `treaty_${Date.now()}`
      const treaty: Treaty = {
        id: treatyId,
        type: treatyType,
        participants: [playerFactionId.value, targetFactionId],
        terms,
        duration: getTreatyDuration(treatyType),
        signedAt: Date.now(),
        isActive: true
      }

      treaties.value[treatyId] = treaty

      // 更新关系
      updateRelationship(targetFactionId, {
        opinion: 20,
        trust: 10,
        status: getNewDiplomaticStatus(relationship.status, treatyType)
      })

      // 添加到双方的条约列表
      relationship.treaties.push(treatyId)
      targetFaction.relationships[playerFactionId.value]?.treaties.push(treatyId)

      return true
    }

    return false
  }

  function declarWar(targetFactionId: string): boolean {
    const targetFaction = factions.value[targetFactionId]
    const playerFaction = factions.value[playerFactionId.value]
    
    if (!targetFaction || !playerFaction) return false

    // 取消所有现有条约
    const relationship = playerFaction.relationships[targetFactionId]
    if (relationship) {
      relationship.treaties.forEach(treatyId => {
        const treaty = treaties.value[treatyId]
        if (treaty) {
          treaty.isActive = false
        }
      })
      relationship.treaties = []

      // 更新关系状态
      updateRelationship(targetFactionId, {
        status: 'war',
        opinion: -50,
        trust: -30
      })
    }

    // 影响与其他派系的关系
    Object.keys(factions.value).forEach(factionId => {
      if (factionId !== playerFactionId.value && factionId !== targetFactionId) {
        const otherRelation = targetFaction.relationships[factionId]
        if (otherRelation && otherRelation.status === 'allied') {
          // 盟友可能对玩家产生负面看法
          updateRelationship(factionId, { opinion: -20 })
        }
      }
    })

    return true
  }

  function sendGift(targetFactionId: string, resources: any[]): boolean {
    if (!resourcesStore.canAfford(resources)) return false
    if (!resourcesStore.payCosts(resources)) return false

    const giftValue = resources.reduce((total, resource) => total + resource.amount, 0)
    const opinionGain = Math.min(giftValue / 100, 30) // 最多+30好感度

    updateRelationship(targetFactionId, {
      opinion: opinionGain,
      trust: opinionGain * 0.5
    })

    return true
  }

  function startDiplomaticMission(targetFactionId: string, missionType: DiplomaticMission['type']): boolean {
    const targetFaction = factions.value[targetFactionId]
    if (!targetFaction) return false

    const missionId = `mission_${Date.now()}`
    const mission: DiplomaticMission = {
      id: missionId,
      type: missionType,
      target: targetFactionId,
      duration: getMissionDuration(missionType),
      progress: 0,
      success_chance: calculateMissionSuccessChance(targetFaction, missionType),
      rewards: getMissionRewards(missionType),
      risks: getMissionRisks(missionType)
    }

    activeMissions.value[missionId] = mission
    return true
  }

  function updateMissions(deltaTime: number) {
    Object.entries(activeMissions.value).forEach(([missionId, mission]) => {
      mission.progress += deltaTime / mission.duration
      
      if (mission.progress >= 1) {
        completeMission(missionId)
      }
    })
  }

  function completeMission(missionId: string) {
    const mission = activeMissions.value[missionId]
    if (!mission) return

    const success = Math.random() < mission.success_chance

    if (success) {
      // 应用奖励
      mission.rewards.forEach(reward => {
        applyMissionReward(mission.target, reward)
      })
    } else {
      // 应用风险后果
      mission.risks.forEach(risk => {
        if (Math.random() < risk.probability) {
          applyMissionRisk(mission.target, risk)
        }
      })
    }

    delete activeMissions.value[missionId]
  }

  function updateRelationship(targetFactionId: string, changes: Partial<Relationship>) {
    const playerFaction = factions.value[playerFactionId.value]
    const targetFaction = factions.value[targetFactionId]
    
    if (!playerFaction || !targetFaction) return

    const relationship = playerFaction.relationships[targetFactionId]
    if (!relationship) return

    // 应用变化
    if (changes.opinion !== undefined) {
      relationship.opinion = Math.max(-100, Math.min(100, relationship.opinion + changes.opinion))
    }
    
    if (changes.trust !== undefined) {
      relationship.trust = Math.max(0, Math.min(100, relationship.trust + changes.trust))
    }
    
    if (changes.fear !== undefined) {
      relationship.fear = Math.max(0, Math.min(100, relationship.fear + changes.fear))
    }

    if (changes.status) {
      relationship.status = changes.status
    }

    // 更新对方的关系记录
    const reverseRelation = targetFaction.relationships[playerFactionId.value]
    if (reverseRelation) {
      if (changes.opinion !== undefined) {
        reverseRelation.opinion = relationship.opinion
      }
      if (changes.trust !== undefined) {
        reverseRelation.trust = relationship.trust
      }
      if (changes.status) {
        reverseRelation.status = relationship.status
      }
    }
  }

  // 辅助函数
  function calculateTreatyAcceptance(faction: Faction, treatyType: Treaty['type'], terms: any[]): number {
    let baseChance = 0.5
    const relationship = faction.relationships[playerFactionId.value]
    
    if (!relationship) return 0

    // 基于好感度调整
    baseChance += (relationship.opinion / 100) * 0.3

    // 基于信任度调整
    baseChance += (relationship.trust / 100) * 0.2

    // 基于派系性格调整
    switch (treatyType) {
      case 'trade':
        baseChance += (faction.personality.trade / 100) * 0.3
        break
      case 'military':
        baseChance += (faction.personality.cooperation / 100) * 0.2
        break
      case 'alliance':
        baseChance += (faction.personality.cooperation / 100) * 0.4
        baseChance -= (faction.personality.aggression / 100) * 0.2
        break
    }

    return Math.max(0, Math.min(1, baseChance))
  }

  function getNewDiplomaticStatus(currentStatus: any, treatyType: Treaty['type']): any {
    switch (treatyType) {
      case 'alliance':
        return 'allied'
      case 'non_aggression':
        return currentStatus === 'war' ? 'neutral' : currentStatus
      default:
        return currentStatus
    }
  }

  function getTreatyDuration(treatyType: Treaty['type']): number {
    const durations = {
      non_aggression: 3600000, // 1小时
      trade: 7200000, // 2小时
      research: 5400000, // 1.5小时
      military: 10800000, // 3小时
      alliance: -1, // 永久
      vassalage: -1 // 永久
    }
    return durations[treatyType] || 3600000
  }

  function getMissionDuration(missionType: DiplomaticMission['type']): number {
    const durations = {
      establish_embassy: 1800000, // 30分钟
      trade_negotiation: 900000, // 15分钟
      intelligence_gathering: 2700000, // 45分钟
      cultural_exchange: 3600000, // 1小时
      military_cooperation: 1800000 // 30分钟
    }
    return durations[missionType] || 1800000
  }

  function calculateMissionSuccessChance(faction: Faction, missionType: DiplomaticMission['type']): number {
    const relationship = faction.relationships[playerFactionId.value]
    if (!relationship) return 0.3

    let baseChance = 0.5
    baseChance += (relationship.opinion / 100) * 0.2
    baseChance += (relationship.trust / 100) * 0.15

    return Math.max(0.1, Math.min(0.9, baseChance))
  }

  function getMissionRewards(missionType: DiplomaticMission['type']) {
    // 返回任务奖励配置
    return []
  }

  function getMissionRisks(missionType: DiplomaticMission['type']) {
    // 返回任务风险配置
    return []
  }

  function applyMissionReward(targetFactionId: string, reward: any) {
    // 应用任务奖励
  }

  function applyMissionRisk(targetFactionId: string, risk: any) {
    // 应用任务风险
  }

  function getFaction(factionId: string): Faction | undefined {
    return factions.value[factionId]
  }

  function getRelationship(factionId: string): Relationship | undefined {
    const playerFaction = factions.value[playerFactionId.value]
    return playerFaction?.relationships[factionId]
  }

  return {
    // 状态
    factions,
    treaties,
    diplomaticActions,
    activeMissions,
    playerFactionId,
    
    // 计算属性
    alliedFactions,
    hostileFactions,
    neutralFactions,
    activeTreaties,
    diplomaticPower,
    
    // 动作
    initializeFactions,
    proposeTreaty,
    declarWar,
    sendGift,
    startDiplomaticMission,
    updateMissions,
    updateRelationship,
    getFaction,
    getRelationship
  }
})